//
//  QKSearchView.swift
//  HHSwift
//
//  Created by 华宏 on 2019/10/9.
//  Copyright © 2019 huahong. All rights reserved.
//

import UIKit

protocol QKSearchViewDelegate {
    func searchButtonClicked(_ searchBar:UISearchBar) -> Void
}

class QKSearchView: UIView {

    typealias QKSearchBlock = (_ searchBar:UISearchBar) -> Void
    var searchBlock : QKSearchBlock?
    
    var delegate:QKSearchViewDelegate?
    
    var placeholder : String?{
       
//先willSet,再didSet (newValue才是当前设置的值),
//        willSet{
//            print("newValue:\(newValue ?? "nil")")
//          self.searchBar.placeholder = newValue
//        }
        
        didSet{
            print("oldValue:\(oldValue ?? "nil")")
            self.searchBar.placeholder = placeholder
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(self.searchBar)
        self.addSubview(self.searchButton)
        
        self.backgroundColor = .white
//        self.layer.borderWidth = 0.5
//        self.layer.borderColor = UIColor.gray.cgColor
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width - 50, height: self.bounds.size.height))
        searchBar.backgroundColor = .white
        searchBar.delegate = self
        searchBar.returnKeyType = .search
//        searchBar.prompt = "prompt"
//        searchBar.setSearchFieldBackgroundImage(UIImage.image(withColor: .white, size: CGSize(width: 1, height: 1)), for: UIControl.State.normal)
        searchBar.barTintColor = .brown
        searchBar.searchBarStyle = .default
        searchBar.backgroundImage = UIImage.image(withColor: .white, size: CGSize(width: 1, height: 1))
        let textField:UITextField = searchBar.value(forKey: "searchField") as! UITextField
        textField.font = UIFont.systemFont(ofSize: 12)
        return searchBar
    }()
    
    lazy var searchButton: UIButton = {
        let button = UIButton.init(type: UIButton.ButtonType.custom)
        button.frame = CGRect.init(x: self.bounds.size.width - 45, y: 0, width: 40, height: self.bounds.size.height)
        button.setTitle("搜索", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.addTarget(self, action: #selector(searchAction(sender:)), for: .touchUpInside)
        return button
    }()
   
    
    @objc func searchAction(sender:UIButton){
        searchBar.resignFirstResponder()
        self.delegate?.searchButtonClicked(self.searchBar)
        self.searchBlock?(searchBar)

       }
}

   

extension QKSearchView:UISearchBarDelegate {
   
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
        searchBar.resignFirstResponder()
        self.delegate?.searchButtonClicked(self.searchBar)
        self.searchBlock?(searchBar)
    }
}
